﻿using AutoMapper;
using B.Z.BasicData.API.Read.DTO;
using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MediatR;
using Newtonsoft.Json;

namespace B.Z.BasicData.API.Read.Application.Role
{
    public class UserRoleQueryCommandHandler : IRequestHandler<UserRoleQueryCommand, APIResult<UserNameDto>>
    {
        private readonly IBaseRepository<T_UserRole> urRepository;
        private readonly IBaseRepository<T_User> userRepository;
        private readonly IMapper mapper;
        public UserRoleQueryCommandHandler(IBaseRepository<T_UserRole> urRepository, IBaseRepository<T_User> userRepository, IMapper mapper)
        {
            this.urRepository = urRepository;
            this.userRepository = userRepository;
            this.mapper = mapper;
        }

        public Task<APIResult<UserNameDto>> Handle(UserRoleQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserNameDto> result = new APIResult<UserNameDto>();
            result.Code = APIEnum.faile;
            result.Message = "获取失败";
            UserNameDto dto = new UserNameDto();
            var userlist = urRepository.GetAll().Where(p => p.Rid == request.Rid).Select(x =>Convert.ToInt32(x.Uid)).ToList();
            if (userlist.Count() != 0) 
            {
                result.Code = APIEnum.ok;
                result.Message = "获取成功";
                var deparmentId = (userRepository.GetAll().FirstOrDefault(x => x.Id == userlist[0])!).DepartMentId;
                dto.IdList = userlist;
                dto.DeparmentId = Convert.ToInt32(deparmentId);
                dto.UserName = userRepository.GetAll().Where(p => userlist.Contains(p.Id)).ToList();
                result.Data = dto;
                return Task.FromResult(result);
            }
            
            
            result.Data = dto;
            return Task.FromResult(result);
        }
    }
}
